package lxgorm

import (
	gormredis "gitee.com/lxgow/lxmysql/gorm/common/redis"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"sync"
)

// funx
// 创建时间:下午12:13
// 创建人:lixu

const (
	CACHE_TYPE_REDIS   = "redis"
	CACHE_TYPE_PROCESS = "process"
)

var (
	// GLOBALDBS 全局数据库链接对象
	GLOBALDBS = make(map[string]*gorm.DB)
	// 默认配置
	defaultSetting = GormSettings{
		Debug: false,
		GormConfig: gorm.Config{
			Logger: logger.Default.LogMode(logger.Silent), SkipDefaultTransaction: true,
		},
		Cache: MCache{
			Type:      "redis",
			CacheTime: 300,
		},
	}
	// 互斥锁
	settingMutex sync.Mutex
)

// SetDefaultSetting 设置默认参数
func SetDefaultSetting(setting GormSettings) {
	settingMutex.Lock()
	defer settingMutex.Unlock()
	defaultSetting = setting
}

// New 实例化数据库
func New(config GormSettings) (errs []error) {

	settingMutex.Lock()
	defer settingMutex.Unlock()

	defaultSetting = config

	if config.Cache.Redis.Host != "" {
		gormredis.NewRedis(config.Cache.Redis)
	}

	for _, conn := range config.Conns {
		if GLOBALDBS[conn.Name] != nil {
			continue
		}
		var err error
		GLOBALDBS[conn.Name], err = gorm.Open(mysql.Open(conn.Conn), &defaultSetting.GormConfig)
		if err != nil {
			errs = append(errs, err)
		}
	}
	return
}
